using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Framework.Core.Xml
{
    internal class XElementGroupingEqualityComparer : IEqualityComparer<IGrouping<int, XElement>>
    {
        public bool Equals(IGrouping<int, XElement> x, IGrouping<int, XElement> y)
        {
            var xCount = x.Count();
            var yCount = y.Count();
            var sameKeyAndSameCount = x.Key == y.Key && xCount == yCount;

            if (sameKeyAndSameCount)
            {
                for (var i = 0; i < x.Count(); i++)
                {
                    var equals = XNode.DeepEquals(x.ElementAt(i), y.ElementAt(i));
                    if (!equals)
                    {
                        return false;
                    }
                }
            }

            return sameKeyAndSameCount;
        }

        public int GetHashCode(IGrouping<int, XElement> obj)
        {
            return GetHash(obj.First());
        }

        public static int GetHash(XElement xElement)
        {
            var hashCode = 295 ^ xElement.Name.LocalName.GetHashCode();

            var aggregate = xElement.Attributes().Aggregate(hashCode,
                                                            (current, a) => 300 ^ current ^ a.Value.GetHashCode());
            return aggregate;
        }
    }
}